package com.itheima.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.itheima.mapper.AddressBookMapper;
import com.itheima.pojo.AddressBook;
import com.itheima.service.AddressBookService;
import com.itheima.utils.BaseContext;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * @Author: 放学后海堤日记
 * @Date: 2023/4/18 17:16
 * @Desc:
 */
@Service
@Slf4j
public class AddressBookServiceImpl implements AddressBookService {
    @Autowired
    private AddressBookMapper addressBookMapper;

    @Override
    public List<AddressBook> listAll() {
        return addressBookMapper.selectList(null);
    }

    @Override
    public void setDefault(AddressBook addressBook) {
        QueryWrapper<AddressBook> wrapper = new QueryWrapper<>();
        wrapper.eq("is_default", 1);

        AddressBook addressBook1 = addressBookMapper.selectOne(wrapper);
        addressBook1.setIsDefault(0);
        addressBookMapper.updateById(addressBook1);

        addressBook.setIsDefault(1);
        addressBookMapper.updateById(addressBook);
    }

    @Override
    public AddressBook findById(Long id) {
        return addressBookMapper.selectById(id);
    }

    @Override
    public void updateAddressBook(AddressBook addressBook) {
        addressBookMapper.updateById(addressBook);
    }

    @Override
    public void addAddressBook(AddressBook addressBook) {
        addressBook.setUserId(BaseContext.getCurrentId());
        addressBookMapper.insert(addressBook);
    }

    @Override
    public void deleteaddAddressBook(Long id) {
        addressBookMapper.deleteById(id);
    }

    @Override
    public AddressBook findDefaultAddressBook() {
        QueryWrapper<AddressBook> wrapper = new QueryWrapper<>();
        wrapper.eq("is_default", 1);

        return addressBookMapper.selectOne(wrapper);
    }
}
